package com.jiangtai.training.ui.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.RcvData
import android.util.Log
import com.blankj.utilcode.util.ToastUtils
import com.jiangtai.training.bean.*
import com.jiangtai.training.constant.Constant
import com.jiangtai.training.event.RefreshLocEvent
import com.jiangtai.training.event.RefreshPracticeEvent
import com.jiangtai.training.event.RefreshScoreStateEvent
import com.jiangtai.training.util.HexUtil
import com.jiangtai.training.util.Preference
import org.greenrobot.eventbus.EventBus
import org.litepal.LitePal
import java.nio.charset.Charset
import java.util.*

/**
 * Created by heCunCun on 2021/3/12
 * 433  信息接收
 * 777579616e776569a1a2a3a4a5a6a7a8
 */
class SignalReceiver : BroadcastReceiver() {
    private var currentTaskId: String by Preference(Constant.CURRENT_TASK_ID, "")
    private var phoneId: String by Preference(Constant.PHONE_ID, "")
    override fun onReceive(context: Context?, intent: Intent?) {
        intent?.let {
            val parser = it.getParcelableExtra<RcvData>("result")
            //解析后入表  考核成绩表Score  训练成绩表
            val str = HexUtil.formatHexString(parser.getrcvdata(), true).toUpperCase(Locale.ROOT)
            Log.e("SignalReceiver", "onReceive: >>>>>>>>>>>>>$str")
           // ToastUtils.showShort("SignalReceiver==>>>> $str")
            val content = parser.getrcvdata().toList()
            when (content[0]) {//命令字
                0x51.toByte() -> {   //手持收到考核开始指令
                    //判断是否是可接受的手持机
                    if (currentTaskId == "") {
                        ToastUtils.showShort("先点击开始任务按钮")
                        return
                    }
                    val pId = HexUtil.bcd2Str(content.subList(4, 5).toByteArray())
                    Log.e("SignalReceiver", "考核开始 data phoneId=$pId,currentPhoneId =$phoneId")
                    if (pId != phoneId) {//不是目标手持不解析
                        if (phoneId == "") {
                            ToastUtils.showShort("先设置PhoneId")
                        }
                        return
                    }
                    //WATCHID 表示当前考核人员ID。
                    //val watchId = HexUtil.bcd2Str(content.subList(5, 5 + 5).toByteArray())
                    val personId = HexUtil.formatHexString(content.subList(5, 5 + 16).toByteArray()).toUpperCase(
                        Locale.ROOT
                    )
                    // Log.e("SignalReceiver", "watchId=$watchId")
                    Log.e("SignalReceiver", "personId=$personId")
                    //根据watchId  查人员表 改成考核中
                    val personList =
                        LitePal.where("personId = ?", personId).find(Person::class.java)
                    if (personList.isNotEmpty()) {
                        val person = personList[0]
                        //新建score记录
                        val scoreBean = Score()
                        scoreBean.personId = person.personId
                        //赋值考核项目名称
                        when (content[2]) {
                            0xE0.toByte() -> {
                                when (content[3]) {
                                    0x11.toByte() -> {// 引体向上
                                        scoreBean.projectId = HexUtil.formatHexString(
                                            content.subList(2, 4).toByteArray(), false
                                        ).toUpperCase(Locale.ROOT)
                                        scoreBean.projectName = "引体向上"
                                    }
                                    0x12.toByte() -> {//仰卧起坐
                                        scoreBean.projectId = HexUtil.formatHexString(
                                            content.subList(2, 4).toByteArray(), false
                                        ).toUpperCase(Locale.ROOT)
                                        scoreBean.projectName = "仰卧起坐"
                                    }
                                    0x16.toByte() -> {//身高体重
                                        scoreBean.projectId = HexUtil.formatHexString(
                                            content.subList(2, 4).toByteArray(), false
                                        ).toUpperCase(Locale.ROOT)
                                        scoreBean.projectName = "身高体重"
                                    }
                                    0x27.toByte() -> {//蛇形跑
                                        scoreBean.projectId = HexUtil.formatHexString(
                                            content.subList(2, 4).toByteArray(), false
                                        ).toUpperCase(Locale.ROOT)
                                        scoreBean.projectName = "蛇形跑"
                                    }
                                    0x26.toByte() -> {//俯卧撑
                                        scoreBean.projectId = HexUtil.formatHexString(
                                            content.subList(2, 4).toByteArray(), false
                                        ).toUpperCase(Locale.ROOT)
                                        scoreBean.projectName = "俯卧撑"
                                    }
                                    else -> {
                                        //未知项目
                                    }
                                }
                            }
                            0xE1.toByte() -> {
                                when (content[3]) {
                                    0x00.toByte() -> {//3000M
                                        scoreBean.projectId = HexUtil.formatHexString(
                                            content.subList(2, 4).toByteArray(), false
                                        ).toUpperCase(Locale.ROOT)
                                        scoreBean.projectName = "3000M"
                                    }
                                    else -> {

                                    }
                                }

                            }

                        }
                        //scoreBean.taskId = "1.0"
                        scoreBean.taskId = currentTaskId
                        scoreBean.state = Constant.STATE_RUNNING //考核中
                        scoreBean.startTime = System.currentTimeMillis()//开始时间

                        val find = LitePal.where(
                            "taskId like ? and projectId like ? and state like ? and personId like ?",
                                currentTaskId,
                            scoreBean.projectId,
                            Constant.STATE_RUNNING.toString(),
                                scoreBean.personId
                        ).find(Score::class.java)
                        if (find.isEmpty()){
                            scoreBean.save()//保存数据表 刷新目标文件
                            EventBus.getDefault().post(RefreshScoreStateEvent())
                        }else{
                            Log.e("SignalReceiver","该科目已开始考核,不再处理")
                        }



                    } else {
                        Log.e("SignalReceiver", "考核人员未录入表")
                    }


                }
                0x60.toByte(),0x61.toByte() -> {//收到上报成绩
                    val pId = HexUtil.bcd2Str(content.subList(5, 6).toByteArray())
                    Log.e(
                        "SignalReceiver",
                        "收到成绩上报 data phoneId=$pId,currentPhoneId =$phoneId"
                    )
                    if (pId != phoneId) {//不是目标手持不解析
                        return
                    }
                    val projectId =
                        HexUtil.formatHexString(content.subList(3, 5).toByteArray(), false)
                            .toUpperCase(Locale.ROOT)
                    //WATCHID 表示当前考核人员ID。
                    //  val watchId = HexUtil.bcd2Str(content.subList(6, 6 + 5).toByteArray())
                    val personID = HexUtil.formatHexString(content.subList(6, 6 + 16).toByteArray()).toUpperCase(Locale.ROOT)
                    Log.e("SignalReceiver", "personId=$personID")
                    when (content[2]) {
                        0x01.toByte() -> {
                            //考核成绩  查询已开始的考核成绩记录
                            //根据watchId  查人员表 改成考核完成
                            val personList =
                                LitePal.where("personId = ?", personID).find(Person::class.java)
                            if (personList.isNotEmpty()) {
                                val personId = personList[0].personId
                                personList[0].updateTime = System.currentTimeMillis()
                                personList[0].save()
                                val scoreList = LitePal.where(
                                    "taskId=? and personId=? and projectId=?",
                                    currentTaskId,
                                    personId,
                                    projectId
                                ).find(Score::class.java)
                                if (scoreList.isNotEmpty()) {
                                    val scoreBean = scoreList[0]
                                    scoreBean.endTime = System.currentTimeMillis()
                                    if (projectId == "E016") {//身高体重
                                        val height = HexUtil.bytes1ToInt2(
                                            content.subList(6 + 16, 6 + 17).toByteArray(), 0
                                        )
                                        val weight = HexUtil.bytes1ToInt2(
                                            content.subList(6 + 17, 6 + 18).toByteArray(), 0
                                        )
                                        scoreBean.score = "${height}cm,${weight}kg"
                                    } else if(projectId=="E027"){
                                        val second = HexUtil.bytes1ToInt2(
                                            content.subList(6 + 16, 6 + 17).toByteArray(), 0
                                        )
                                        val mSecond = HexUtil.bytes1ToInt2(
                                            content.subList(6 + 17, 6 + 18).toByteArray(), 0
                                        )
                                        scoreBean.score = "${second}s,${mSecond}ms"


                                    }else {
                                      val value = HexUtil.bytes2ToInt2(
                                            content.subList(6 + 16, 6 + 18).toByteArray(), 0
                                        ).toString()
                                        var unit =""
                                        //onReceive: >>>>>>>>>>>>>61 16 01 E1 00 02 77 75 79 61 6E 77 65 69 A1 A2 A3 A4 A5 A6 A7 B0 00 6B 10 EE
                                        //onReceive: >>>>>>>>>>>>>61 16 01 E1 00 02 77 75 79 61 6E 77 65 69 A1 A2 A3 A4 A5 A6 A7 B0 00 F1 10 74
                                       when(projectId){
                                           "E011","E012", "E026"->{  scoreBean.score ="${value}次"}
                                           "E100"->{
                                               val min = value.toInt()/60
                                               val second = value.toInt()%60
                                               scoreBean.score="${min}分${second}秒"
                                           }
                                           else->{}
                                       }
                                    }
                                    scoreBean.state = Constant.STATE_FINISHED
                                    scoreBean.save()
                                    EventBus.getDefault().post(RefreshScoreStateEvent())
                                } else {
                                    Log.e("SignalReceiver", "成绩表查不到此考核成绩开始记录")
                                    ToastUtils.showShort("成绩表查不到${personList[0].name}考核成绩开始记录")
                                }
                            } else {
                                Log.e("SignalReceiver", "watchId  查人员表不存在此人")
                            }

                        }
                        0x02.toByte() -> {
                            //训练成绩
                            val normalPersonList =
                                LitePal.where("personId=?", personID.toUpperCase(Locale.ROOT)).find(NormalPerson::class.java)
                            if (normalPersonList.isNotEmpty()) {
                                val personId = normalPersonList[0].personId
                                val normalScoreList = LitePal.where("personId=? and projectId=?", personId,projectId)
                                    .find(NormalScore::class.java)
                                if (normalScoreList.isNotEmpty()) {
                                    val normalScoreBean = normalScoreList.last()
                                    normalScoreBean.uploadTime = System.currentTimeMillis()//当前结束时间
                                    if (projectId == "E016") {//身高体重
                                        val height = HexUtil.bytes1ToInt2(
                                            content.subList(6 + 16, 6 + 17).toByteArray(), 0
                                        )
                                        val weight = HexUtil.bytes1ToInt2(
                                            content.subList(6 + 17, 6 + 18).toByteArray(), 0
                                        )
                                        normalScoreBean.score = "${height}cm,${weight}kg"
                                    } else if(projectId=="E027"){
                                        val second = HexUtil.bytes1ToInt2(
                                            content.subList(6 + 16, 6 + 17).toByteArray(), 0
                                        )
                                        val mSecond = HexUtil.bytes1ToInt2(
                                            content.subList(6 + 17, 6 + 18).toByteArray(), 0
                                        )
                                        normalScoreBean.score = "${second}s,${mSecond}ms"
                                    }else{
                                       val  value= HexUtil.bytes2ToInt2(
                                            content.subList(6 + 16, 6 + 18).toByteArray(), 0
                                        ).toString()

                                        when(projectId){
                                            "E011","E012", "E026"->{  normalScoreBean.score ="${value}次"}
                                            "E100"->{
                                              val min = value.toInt()/60
                                                val second = value.toInt()%60
                                                normalScoreBean.score="${min}分${second}秒"
                                            }
                                            else->{}
                                        }
                                    }
                                    normalScoreBean.save()
                                    //刷新训练人员表和成绩表
                                    EventBus.getDefault().post(RefreshPracticeEvent())

                                } else {
                                    Log.e("SignalReceiver", "训练表  查不到此人开始训练成绩记录")
                                }
                            } else {
                                Log.e("SignalReceiver", "训练表  查不到此人")
                            }

                        }
                        else -> {
                        }
                    }

                }
                0x52.toByte() -> {//
                    val pId = HexUtil.bcd2Str(content.subList(5, 6).toByteArray())
                    Log.e("SignalReceiver", "训练/考核开始 data phoneId=$pId,currentPhoneId =$phoneId")
                    if (pId != phoneId) {//不是目标手持不解析
                        return
                    }
                    when (content[2]) {
                        0x01.toByte() -> {//考核开始
                        }
                        0x02.toByte() -> {//训练开始l
                            val normalPerson: NormalPerson
                            val projectId =
                                HexUtil.formatHexString(content.subList(3, 5).toByteArray(), false)
                                    .toUpperCase(Locale.ROOT)
                            val userId = HexUtil.formatHexString(
                                content.subList(6, 6 + 16).toByteArray(), false
                            ).toUpperCase(Locale.ROOT)
                            val normalPersonList =
                                LitePal.where("personId=?", userId).find(NormalPerson::class.java)
                            if (normalPersonList.isEmpty()) {
                                //WATCHID 表示当前考核人员ID。
                                val name = String(
                                    content.subList(6 + 16, 6 + 16 + 11).toByteArray(),
                                    Charset.forName("GB2312")
                                )
                                normalPerson = NormalPerson(name, userId)
                                normalPerson.save()
                            } else {
                                normalPerson = normalPersonList[0]
                            }

                            //新建训练记录
                            val normalScore = NormalScore()
                            normalScore.personId = normalPerson.personId
                            normalScore.projectId = projectId
                            var projectName = ""
                            when (projectId) {
                                "E011" -> {
                                    projectName = "引体向上"
                                }
                                "E012" -> {
                                    projectName = "仰卧起坐"
                                }
                                "E016" -> {
                                    projectName = "身高体重"
                                }
                                "E027" -> {
                                    projectName = "蛇形跑"
                                }
                                "E026" -> {
                                    projectName = "俯卧撑"
                                }
                                "E100" -> {
                                    projectName = "3000M"
                                }
                                else -> {
                                }
                            }
                            normalScore.projectName = projectName
                            normalScore.startTime = System.currentTimeMillis()
                            normalScore.save()
                            //刷新训练人员表和成绩表
                            EventBus.getDefault().post(RefreshPracticeEvent())
                        }
                        else -> {
                        }
                    }

                }
                0x55.toByte() -> {//腕表3公里考核上报定位信息
                    val pId = HexUtil.bcd2Str(content.subList(4, 5).toByteArray())
                    Log.e("SignalReceiver", "定位信息上报开始 data phoneId=$pId,currentPhoneId =$phoneId")
                    if (pId != phoneId) {//不是目标手持不解析
                        return
                    }
                    val projectId = HexUtil.formatHexString(content.subList(2, 4).toByteArray())
                        .toUpperCase(Locale.ROOT)
                    val personID = HexUtil.formatHexString(content.subList(5, 5 + 16).toByteArray()).toUpperCase(Locale.ROOT)
                    //根据personID 经纬度表
                    val heartRate =
                        HexUtil.bytes1ToInt2(content.subList(5 + 16, 5 + 17).toByteArray(), 0)
                    val lng =
                        HexUtil.bytesToInt2(content.subList(5 + 17, 5 + 17 + 4).toByteArray(), 0)
                    val lat = HexUtil.bytesToInt2(
                        content.subList(5 + 17 + 4, 5 + 17 + 4 + 4).toByteArray(), 0
                    )
                    //经\纬度：长度4字节，小数点左移7位可得到真实值，正数表示东经，北纬；负数表示西经
                    Log.e(
                        "SignalReceiver",
                        "personID=$personID,heartRate=$heartRate,lat = ${lat/10000000f},lng =${lng/10000000f}"
                    )
                    val locationInfoBean = LocationInfoBean(
                        lat / 10000000.0,
                        lng / 10000000.0,
                        heartRate,
                        personID,
                        projectId,
                        System.currentTimeMillis(),
                        currentTaskId
                    )
                    locationInfoBean.save()

                    EventBus.getDefault().post(RefreshLocEvent())
                }
                else -> {

                }
            }


        }


    }

}
